package kr.couponplay.android.support;

import java.io.IOException;
import java.io.InputStream;

import kr.couponplay.android.domain.DataAccessException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

public class HttpUtils<T> {
	private static final int TIMEOUT = 7000;
	public static String executeToStr(String url) throws Exception {
        return executeToStr(url, TIMEOUT);
	}
	
	public static String executeToStr(String url, int setTimeout) throws Exception {
		HttpResponse response = execute(url, setTimeout);
		return EntityUtils.toString(response.getEntity(), "UTF-8");
	}

	
	public static InputStream executeToIn(String url) throws Exception {
		HttpResponse response = execute(url, TIMEOUT);
		return response.getEntity().getContent();
	}
	
	private static HttpResponse execute(String url, int setTimeout) throws IOException, ClientProtocolException {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, setTimeout);
		HttpConnectionParams.setSoTimeout(params, setTimeout);
		
		HttpGet method = new HttpGet(url);
		method.setHeader("Connection", "Keep-Alive");
		HttpResponse response = httpClient.execute(method);
		int status = response.getStatusLine().getStatusCode();
		if (status != HttpStatus.SC_OK) {
			throw new DataAccessException( "http response status error!! status is " + status );
		}
		return response;
	}
}
